package cn.compose.online.api;

import cn.compose.common.util.StringUtils;
import cn.compose.online.enums.ResultTypeEnum;
import cn.compose.online.service.JavaComplieService;
import cn.compose.online.vo.ResultResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@Slf4j
@RequestMapping("/run")
public class CompileController {
    @Resource
    private JavaComplieService javaComplieService;


    /**
     * 执行编译
     *
     * @param code groovy代码
     * @return 编译结果
     */
    @RequestMapping("/compile")
    public ResultResponse compile(@RequestParam(value = "code") String code,
                                  @RequestParam(value = "method") String method,
                                  @RequestParam(value = "paramsName") String paramsName,
                                  @RequestParam(value = "paramsValue") String paramsValue,
                                  @RequestParam(value = "params", required = false) String params) {
        ResultResponse resultResponse = new ResultResponse();
        try {

            if (StringUtils.isEmpty(code)) {
                return ResultResponse.Build(ResultTypeEnum.error, "执行代码不能为空！");
            }

            if(params.contains("，")){
                return ResultResponse.Build(ResultTypeEnum.error, "填入参数需使用英文逗号分隔！");
            }

            //替换参数
            String[] name = paramsName.split(",");
            String[] value = paramsValue.split(",");
            String[] param = params.split(",");
            if (name != null && name.length > 0) {
                if(param.length != name.length){
                    return ResultResponse.Build(ResultTypeEnum.error, "填写的参数个数不对应！");
                }

                for (int i = 0; i < name.length; i++) {
                    code = code.replace(value[i], param[i]);
                }
            }


            long startTime = System.currentTimeMillis();
            Object object = javaComplieService.execute(code, method);
            long endTime = System.currentTimeMillis();
            resultResponse.setExecuteDurationTime(endTime - startTime);
            if (object == null) {
                return ResultResponse.Build(ResultTypeEnum.error, "编译执行出错了！ 错误信息:" + object);
            }

            resultResponse.setExecuteResult(object.toString());
            resultResponse.setResultTypeEnum(ResultTypeEnum.ok);
            resultResponse.setMessage("ok");
            return resultResponse;
        } catch (Exception e) {
            log.error("编译执行出错了！ 错误信息:", e);
            return ResultResponse.Build(ResultTypeEnum.error, "编译执行出错了！ 错误信息:" + e.getMessage());
        }
    }
}
